/**
 * 压缩图片到指定大小
 * @param baseImg base64图片
 * @param maxSize 单位kb
 */
export function compressImg(baseImg, maxSize = 100) {
  return new Promise((resolve) => {
    const size = calcLength(baseImg)
    var img = new Image()
    img.src = baseImg

    let compressedSize = size
    img.onload = () => {
      var width = img.width
      var height = img.height

      let quality = 0.9
      let result = baseImg
      while (compressedSize > maxSize && quality > 0) {
        var canvas = document.createElement('canvas')
        canvas.width = width
        canvas.height = height
        var ctx = canvas.getContext('2d')
        ctx.drawImage(img, 0, 0, width, height)
        result = canvas.toDataURL('image/jpeg', quality)

        compressedSize = calcLength(result)
        quality -= 0.1
      }

      console.log(
        '压缩前: ' +
          size +
          'kb, 压缩后: ' +
          compressedSize +
          'kb, 压缩比例: ' +
          ((compressedSize * 100) / size).toFixed(0) +
          '%'
      )
      resolve(result)
    }
  })
}

function calcLength(baseImg) {
  // 计算图片大小
  const strLength = baseImg.length
  const fileLength = parseInt(strLength - (strLength / 8) * 2)
  return parseInt((fileLength / 1024).toFixed(2))
}
